<template>
  <el-card>
    <el-button :icon="Plus" type="primary" @click="dialogVisible = true"
      >添加</el-button
    >
    <el-table :data="trademarkList" width="100%">
      <el-table-column type="index" label="序号" width="180" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template #default="{ row }">
          <img :src="row.logoUrl" alt="" width="100" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            type="warning"
            :icon="Edit"
            @click="editTrade(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            @click="delList(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9]"
      layout="prev, pager, next, jumper, sizes, total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
  <el-dialog
    v-model="dialogVisible"
    :title="`${ruleForm.id ? '编辑品牌' : '添加品牌'}`"
    width="50%"
  >
    <el-form
      label-width="120px"
      :model="ruleForm"
      :rules="rules"
      ref="ruleFormRef"
    >
      <el-form-item label="品牌名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="imageUrl">
        <el-upload
          class="avatar-uploader"
          action="/app-dev/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="ruleForm.imageUrl"
            :src="ruleForm.imageUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelBtn">取消</el-button>
        <el-button type="primary" @click="addUpdateTrademark">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: "TradeMark",
}
</script>

<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue"
import { ref, onMounted, reactive } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import type { UploadProps, FormInstance, FormRules } from "element-plus"

import {
  reqTradeMarkListApi,
  delTradeMarkApi,
  addTradeMarkApi,
  updateTradeMarkApi,
} from "@/api/product/trademark"
import type { trademarkItem } from "@/api/product/model/trademarkModel"
const pageSize = ref<number>(3)
const currentPage = ref<number>(1)
const total = ref(0)
const trademarkList = ref<trademarkItem[]>([])
const dialogVisible = ref(false)
// 表单验证
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  name: "",
  imageUrl: "",
  id: 0,
})
const rules = reactive<FormRules>({
  name: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  ],
  imageUrl: [
    {
      required: true,
      message: "请选择图片",
      trigger: "blur",
    },
  ],
})
// 请求分页数据函数
const reqTradeMarkList = async () => {
  const result = await reqTradeMarkListApi(currentPage.value, pageSize.value)
  total.value = result.total
  trademarkList.value = result.records
}
onMounted(() => {
  reqTradeMarkList()
})
// 分页器
const handleSizeChange = () => {
  currentPage.value = 1
  reqTradeMarkList()
}
const handleCurrentChange = (newCurrentPage: number) => {
  currentPage.value = newCurrentPage
  reqTradeMarkList()
}
// 删除商品
const delList = async (row: trademarkItem) => {
  ElMessageBox.confirm(`您确认要删除 ${row.tmName} 数据吗?`, "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await delTradeMarkApi(row.id)
    ElMessage.success("删除品牌成功")
    reqTradeMarkList()
  })
}
// upload
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // ruleForm.imageUrl = response.data
  ruleForm.imageUrl = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const typeFiles = ["image/jpeg", "image/jpg", "image/png"]
  if (!typeFiles.includes(rawFile.type)) {
    ElMessage.error("上传图片必须是jpg，png")
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过 2MB!")
    return false
  }
  return true
}
// 添加&修改商品函数
const addUpdateTrademark = () => {
  ruleFormRef.value?.validate(async (valid) => {
    // valid为true，代表表单校验通过
    if (valid) {
      if (ruleForm.id) {
        const { name, imageUrl, id } = ruleForm
        await updateTradeMarkApi({ id, tmName: name, logoUrl: imageUrl })
        ElMessage.success("修改品牌成功")
      } else {
        const { name, imageUrl } = ruleForm
        // 发送请求，添加品牌(更新服务器数据)
        await addTradeMarkApi(name, imageUrl)
        ElMessage.success("添加品牌成功")
      }
      // 清空表单数据
      ruleFormRef.value?.resetFields()
      dialogVisible.value = false
      ruleForm.name = ""
      ruleForm.imageUrl = ""
      ruleForm.id = 0
      reqTradeMarkList()
    }
  })
}
// 编辑按钮点击
const editTrade = (row: trademarkItem) => {
  ruleForm.name = row.tmName
  ruleForm.imageUrl = row.logoUrl
  ruleForm.id = row.id
  dialogVisible.value = true
}
// 取消按钮
const cancelBtn = () => {
  dialogVisible.value = false
  ruleFormRef.value?.clearValidate()
  ruleForm.name = ""
  ruleForm.imageUrl = ""
  ruleForm.id = 0
}
</script>

<style scoped>
.el-table {
  margin: 20px 0;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
